package com.lingjtx.common.redis.config;

import com.lingjtx.common.core.util.StringUtil;
import jakarta.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

import java.net.InetAddress;
import java.net.UnknownHostException;

@Order(1)
@Configuration
public class ServerNodeConfig {

    private static final Logger log = LoggerFactory.getLogger(ServerNodeConfig.class);

    @Value("${server.port:8080}")
    private int serverPort;

    @PostConstruct
    public void init() {
        String appid = StringUtil.getUuid();
        System.setProperty("app.id", appid);  // 可选：将app.id设置为系统属性，方便其他地方访问
        log.info("应用服务 appid: {}", appid);
    }

    public String getNodeId() {
        try {
            InetAddress localHost = InetAddress.getLocalHost();
            String hostAddress = localHost.getHostAddress();
            if ("127.0.0.1".equals(hostAddress)) {
                return String.format("node@%s:%s", localHost.getHostName(), serverPort);
            }
            return String.format("node@%s:%s", hostAddress, serverPort);
        } catch (UnknownHostException e) {
            return getAppId();
        }
    }

    public String getAppId() {
        return System.getProperty("app.id");
    }
}
